
import Vue from 'vue'
import VueRouter from 'vue-router'

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import store from '@/store/index'
import * as util from '@/libs/util.js'

import routes from './routes'


// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

// 导出路由 在 main.js 里使用
const router = new VueRouter({
  base: process.env.VUE_APP_PUBLIC_PATH,
  mode: 'history',
  routes
})

// 免校验token白名单,可以是正则或者字符串
const whiteList = [/\/login*/, '/Err403']

/**
 * 路由拦截
 * 权限验证
 */

function checkWhiteList (to) {
  let acc = false
  for (const item of whiteList) {
    let type = Object.prototype.toString.call(item)

    switch (type) {
      case '[object RegExp]':
        if (item.test(to.path)) {
          acc = true
        }
        break
      case '[object String]':
        if (item === to.path) {
          acc = true
        }
        break
    }
  }
  return acc
}
// import { versionCheck } from './versionCheck'
router.beforeEach(async (to, from, next) => {
  //await versionCheck()
  // 进度条
  if (to.path !== from.path) NProgress.start()

  // 白名单
  if (checkWhiteList(to)) {
    next()
    return
  }
  const token = localStorage.getItem('token')

  // 这里暂时将cookie里是否存有token作为验证是否登录的条件
  // 请根据自身业务需要修改
  // if (!token || token === 'undefined') {
  //   // 没有登录的时候跳转到登录界面
  //   // 携带上登陆成功之后需要跳转的页面完整路径
  //   next({
  //     name: 'login'
  //   })
  //   return
  // }

  next()
})

router.afterEach(to => {
  // 进度条
  NProgress.done()
  // 更改标题
  util.title(to.meta.title)
  store.dispatch('myadmin/pageHistory/pushHistory', to)
})

export default router
